<template>
  <div class="page">
    <div ref="tableHeaderContainer" class="base-search-group-container">
      <form class="base-search" onsubmit="return false;">
        <div class="base-search-repertory-picker">
          {{$t('part.text63')}}：
          <el-date-picker
            @change="seeTime()"
            style="width:226px !important"
            v-model="timeValue"
            type="daterange"
            value-format="timestamp"
            :default-time="['00:00:00', '23:59:59']"
            align="right"
            unlink-panels
            range-separator="-"
            :start-placeholder="$t('common.base.startDate')"
            :end-placeholder="$t('common.base.endDate')"
            :picker-options="pickerOptions2"
          ></el-date-picker>
        </div>
        <div class="customer-list-base-search-group ml_12">
          <el-input v-model="model.keyWord" :placeholder="$t('common.form.preview.subSparePart.pla2')" v-trim:blur>
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
            <el-button slot="append" type='primary' @click="model.pageNum=1;search();trackEventHandler('search')" native-type="submit" v-track="$track.formatParams('KEYWORD_SEARCH')">{{ $t('common.base.search') }}</el-button>
          </el-input>
          <el-button type="plain-third" @click="reset();trackEventHandler('reset')" class="ml_12" v-track="$track.formatParams('RESET_SEARCH')">{{ $t('common.base.reset') }}</el-button>
        </div>
        <div
          class="advanced-search-visible-btn"
          @click.stop="isExpand = !isExpand;trackEventHandler('advSearch')"
        >
          <i class="iconfont icon-filter"></i>
          {{ $t('common.base.advancedSearch') }}
        </div>
      </form>
    </div>

    <base-search-drawer
      :show='isExpand'
      @close='closeDrawer'
      @reset='reset'
      @search='search'
      :show-setting='false'
    >
      <el-form label-position="top" :model='model'>
        <el-form-item :label="$t('common.fields.partName.displayName')">
          <el-select
            popper-class="common-advance-popper"
            style="width: 100%;"
            :value="sparepart.sparepartId"
            @input="chooseSparepart"
            filterable
            clearable
            remote
            :placeholder="$t('task.detail.components.chooseSparePart')"
            :remote-method="fetchSparepart"
            :loading="sparepart.loading"
          >
            <el-option
              v-for="item in sparepart.options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <div class="part-option">
                <p>{{$t('common.label.serialNumber')}}：{{item.serialNumber}}</p>
                <p>{{$t('common.base.name')}}：{{item.name}}</p>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('common.part.category')">
          <el-select :placeholder="$t('common.placeholder.select')" v-model="model.type">
            <el-option :label="$t('common.base.all')" value></el-option>
            <el-option :label="$t('common.form.preview.sparepart.outStock')" value="出库"></el-option>
            <el-option :label="$t('common.form.preview.sparepart.inStock')" value="入库"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('common.base.warehouse')">
          <el-input v-model="model.name" :placeholder="$t('common.placeholder.input2')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('part.field26')">
          <el-input v-model="model.sourceName" :placeholder="$t('common.placeholder.input2')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('part.field8')">
          <el-input v-model="model.targetName" :placeholder="$t('common.placeholder.input2')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('part.field33')">
          <el-input type="number" v-model="model.variation" :placeholder="$t('common.placeholder.input2')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('part.field34')">
          <el-input type="number" v-model="model.number" :placeholder="$t('common.placeholder.input2')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('common.form.type.remark')">
          <el-input v-model="model.remark" :placeholder="$t('common.placeholder.input2')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('common.base.promoter')">
          <publink-select
            class="srp-list-form-item"
            style="width: 100%;"
            :value="model.propser"
            @input="choosePropser"
            filterable
            clearable
            remote
            is-search-user
            :placeholder="$t('common.placeholder.select')"
            :remote-method="fetchUser"
            :loading="user.loading"
          > 
            <el-option
              v-for="item in user.options"
              :key="item.userId"
              :label="item.displayName"
              :origin="item"
              :value="item.userId"
            >
              <div class="srp-user-item">
                <img :src="item.head || '/resource/images/account_userhead.png'" />
                <p>
                  <template v-if="isOpenData && item.staffId">
                    <open-data type="userName" :openid="item.staffId"></open-data>
                  </template>
                  <template v-else>
                    {{item.displayName}} 
                  </template>
                </p>
              </div>
            </el-option>
            
            <!-- <template slot="multiple" slot-scope="{ item }">
              <template v-if="isOpenData && item.staffId">
                <open-data type="userName" :openid="item.staffId"></open-data>
              </template>
              <template v-else>
                {{item.name || item.displayName}}
              </template>
            </template> -->
            
          </publink-select>
          
        </el-form-item>
        <el-form-item :label="$t('part.text63')">
          <el-date-picker
            @change="seeTime()"
            style="width:100%"
            v-model="timeValue"
            type="daterange"
            value-format="timestamp"
            :default-time="['00:00:00', '23:59:59']"
            align="right"
            unlink-panels
            range-separator="-"
            :start-placeholder="$t('common.base.startDate')"
            :end-placeholder="$t('common.base.endDate')"
            :picker-options="pickerOptions2"
          ></el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('part.field38')">
          <el-select :placeholder="$t('common.placeholder.select')" v-model="model.item">
            <el-option-group
              v-for="group in sparepartConfig"
              :key="group.label"
              :label="group.label"
            >
              <el-option
                :label="item"
                :value="item"
                v-for="item in group.options"
                :key="item"
              ></el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('common.form.preview.stock.sparepartStockDisplayName.approveName')">
          <publink-select
            class="srp-list-form-item"
            style="width: 100%;"
            :value="user.userId"
            @input="chooseUser"
            filterable
            clearable
            remote
            is-search-user
            :placeholder="$t('common.placeholder.select')"
            :remote-method="fetchUser"
            :loading="user.loading"
          >
            <el-option
              v-for="item in user.options"
              :key="item.userId"
              :label="item.displayName"
              :value="item.userId"
              :origin="item"
            >
              <div class="srp-user-item">
                <img :src="item.head || '/resource/images/account_userhead.png'" />
                <p>
                  <template v-if="isOpenData && item.staffId">
                    <open-data type="userName" :openid="item.staffId"></open-data>
                  </template>
                  <template v-else>
                    {{item.displayName}} 
                  </template>
                </p>
              </div>
            </el-option>
            <!-- <template slot="multiple" slot-scope="{ item }">
              <template v-if="isOpenData && item.staffId">
                <open-data type="userName" :openid="item.staffId"></open-data>
              </template>
              <template v-else>
                {{item.name || item.displayName}}
              </template>
            </template> -->
          </publink-select>
        </el-form-item>
        <el-form-item :label="$t('common.form.preview.stock.sparepartStockDisplayName.approveNo')">
          <el-input v-model="model.approveNo"></el-input>
        </el-form-item>
      </el-form>
    </base-search-drawer>

    <div ref="tableDoContainer" class="page-panel base-operation-bar-container" style="margin: 0;padding:0;">
      <div class="page-panel-body">
        <!-- 选择仓库（默认全部） -->
        <el-row class="block-col-2">
          <el-select
            v-if="!isStandardEdition && !isExperienceEdition"
            filterable
            :value="repertoryName"
            @input="chooseRepertory"
            class="srp-list-form-item"
            style="width: 150px;"
          >
            <el-option label="全部仓库" value></el-option>
            <el-option v-for="item in repertory" :key="item.id" :value="item.id" :label="item.name"></el-option>
          </el-select>
          <div class="pull-right">
            <el-button-group>
              <el-dropdown
                :hide-on-click="false"
                trigger="click"
                :show-timeout="150"
                v-if="allowImportAndExport && isButtonDisplayed"
                @command="trackEventHandler('moreAction')"
              >
                <span class="el-dropdown-link cur-point mr_12">
                  {{ $t('common.base.moreOperator') }}
                  <i class="iconfont icon-more"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  
                  <el-dropdown-item v-if="isButtonDisplayed">
                    <span class="dropdown-item" @click="exportData(false)" v-track="$track.formatParams('EXPORT', null, 'MORE_ACTIONS')">{{$t('common.base.export')}}</span>
                  </el-dropdown-item>
                  
                  <el-dropdown-item v-if="isButtonDisplayed">
                    <span class="dropdown-item" @click="exportData(true)" v-track="$track.formatParams('EXPORT_ALL', null, 'MORE_ACTIONS')">{{ $t('common.base.exportAll') }}</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>

              <el-dropdown :hide-on-click="false" trigger="click" :show-timeout="150" v-track="$track.formatParams('SELECT_COLUMN')">
                <span class="el-dropdown-link cur-point ml_12">
                  {{ $t('common.base.choiceCol') }}
                  <i class="iconfont icon-more"></i>
                </span>

                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-for="column in columns" :key="column.field">
                    <el-checkbox :value="column.show" @input="chooseColnum(column)">{{column.label}}</el-checkbox>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-button-group>
          </div>
        </el-row>
      </div>
    </div>

    <!-- <div ref="BaseSelectionBarComponent" class="base-selection-wrapper">
      <base-selection-bar
        ref="baseSelectionBar"
        v-model="selected"
        @toggle-selection="toggleSelection"
        @show-panel="() => multipleSelectionPanelShow = true"
      />
    </div> -->

    <div class="table-container">
      <el-table
        v-table-style
        v-loading="pageLoading"
        stripe
        border
        ref="table"
        :data="page.list"
        :height="tableContainerHeight"
        class="bbx-normal-list-box"
        header-row-class-name="base-table-header-v3"
        @select="handleSelection"
        @select-all="handleSelection"
        @header-dragend="headerDragend"
      >
        <template slot="empty">
          <BaseListForNoData v-show="!pageLoading"></BaseListForNoData>
        </template>
        <el-table-column type="selection" fixed align='center' width="44"></el-table-column>

        <el-table-column
          v-for="column in columns"
          :key="column.field"
          v-if="column.show"
          :label="column.label"
          :width="column.width"
          :prop="column.field"
          :min-width="column.minWidth"
          :show-overflow-tooltip="column.showTip !== false"
        >
          <template slot-scope="scope">
            <!-- <template v-if="column.field == 'approveNo'">
               <a
                class="view-detail-btn el-tooltip"
                @click="clickFnc(scope.row)"
              >
                {{scope.row.approveNo}}
              </a>
            </template> else--->
            <template v-if="column.field == 'recordNo'">
              <sample-tooltip :row="scope.row">
                <template slot="content" slot-scope="{isContentTooltip}">
                  <el-tooltip :content="scope.row[column.field]" placement="top" :disabled="!isContentTooltip">
                    <div>{{scope.row.recordNo}}</div>
                  </el-tooltip>
                </template>
              </sample-tooltip>
            </template>
            <template v-else-if="column.field == 'propserName'">
              <template v-if="isOpenData">
                <open-data type="userName" :openid="scope.row.propserStaffId"></open-data>
              </template>
              <template v-else>{{ scope.row.propserName }}</template>
            </template>
            <template v-else-if="column.field == 'executorName'">
              <template v-if="isOpenData">
                <open-data type="userName" :openid="scope.row.executorStaffId"></open-data>
              </template>
              <template v-else>{{ scope.row.executorName }}</template>
            </template>
            <template v-else-if="column.field == 'repertory.name'">
              <template v-if="isOpenData && scope.row.repertory && scope.row.repertory.staffId">
                <open-data type="userName" :openid="scope.row.repertory.staffId"></open-data>
              </template>
              <template v-else>{{scope.row.repertory ? scope.row.repertory.name : ''}}</template>

            </template>
            <template v-else-if="column.field == 'sourceName'">
              <template v-if="isOpenData && scope.row.sourceStaffId">
                <open-data type="userName" :openid="scope.row.targetStaffId"></open-data>
              </template>
              <template v-else>{{ scope.row.sourceName }}</template>
            </template>
            <template v-else-if="column.field == 'targetName'">
              <template v-if="isOpenData && scope.row.targetStaffId">
                <open-data type="userName" :openid="scope.row.targetStaffId"></open-data>
              </template>
              <template v-else>{{ scope.row.targetName }}</template>
            </template>
            <template v-else-if="column.field == 'sparepart.serialNumber'">
              <template v-if="scope.row.sparepart">{{scope.row.sparepart.serialNumber}}</template>
            </template>
            <template v-else-if="column.field == 'sparepart.name'">
              <template
                v-if="scope.row.sparepart"
              >{{scope.row.sparepart && scope.row.sparepart.name}}</template>
            </template>
            <template v-else-if="column.field == 'sparepart.type'">
              <template
                v-if="scope.row.sparepart"
              >{{scope.row.sparepart && scope.row.sparepart.type}}</template>
            </template>
            <template v-else-if="column.field == 'sparepart.standard'">
              <template
                v-if="scope.row.sparepart"
              >{{scope.row.sparepart && scope.row.sparepart.standard}}</template>
            </template>
            <template v-else-if="column.field == 'repertory.name'">
              <template v-if="scope.row.repertory">{{scope.row.repertory.name}}</template>
            </template>
            <template v-else-if="column.field == 'createTime'">
              <template>{{scope.row.createTime | fmt_datetime}}</template>
            </template>
            <template v-else-if="column.field == 'remark'">
              <el-tooltip placement="top" popper-class="common-tooltip">
                <div slot="content" class="pre">{{scope.row[column.field]}}</div>
                <div class="text-overflow-hidden">{{scope.row[column.field]}}</div>
              </el-tooltip>
            </template>
            <template v-else-if="column.field == 'taskNo'">
              <a
                v-if="scope.row.canViewTask"
                class="no-padding el-button no-padding el-button--text"
                style="color: #55B7B4;text-decoration: none;"
                @click.prevent="openTaskDetail(scope.row)">
                {{scope.row.taskNo}}
              </a>
              <span v-else>{{scope.row.taskNo}}</span>
            </template>
            <template v-else-if="column.field == 'customerNumber'">
              <a
                v-if="scope.row.canViewCustomer"
                class="no-padding el-button no-padding el-button--text"
                style="color: #55B7B4;text-decoration: none;"
                @click.prevent="openCustomerDetail(scope.row.customer)">
                {{scope.row.customerNumber}}
              </a>
              <span v-else>{{scope.row.customerNumber}}</span>
            </template>
            <template v-else>{{scope.row[column.field]}}</template>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div ref="tableFooterContainer" class="table-footer bbx-normal-table-footer">
      <div class="list-info">
        <i18n path="common.base.table.totalCount">
          <span place="count" class="level-padding">{{ page.total || 0 }}</span>
        </i18n>
        <i18n path="common.base.table.selectedNth">
          <span
            place="count"
            class="base-table-selected-count"
            @click="multipleSelectionPanelShow = true"
          >{{selected.length}}</span>
        </i18n>
        <template v-if="selected&&selected.length>0">
          <span class="base-table-selected-count" @click="toggleSelection()">{{ $t('common.base.clear') }}</span>
        </template>
      </div>
      <el-pagination
        class="customer-table-pagination"
        background
        @current-change="jump"
        @size-change="pageSizeChange"
        :page-sizes="defaultTableData.defaultPageSizes"
        :page-size="model.pageSize"
        :current-page="model.pageNum"
        layout="prev, pager, next, sizes, jumper"
        :total="page.total"
      ></el-pagination>
    </div>

    <base-export1
      ref="exportPanel"
      v-if="allowImportAndExport"
      :columns="columns"
      :action="partRepertoryRecprtdExport"
      :method="'post'"
    ></base-export1>

    <base-panel :show.sync="multipleSelectionPanelShow" width="420px">
      <h3 slot="title" style="display: flex;justify-content: space-between;align-items: center">
        <span>{{$t('common.base.exportModal.selectedData', {count:selected.length})}}</span>
        <span
          v-if="selected.length"
          class="part-panel-btn"
          @click="toggleSelection()"
          :title="$t('common.base.tip.clearChoseDataTip')"
          data-placement="right"
          v-tooltip
        ></span>
      </h3>

      <div class="part-selected-panel">
        <div class="part-selected-tip" v-if="!selected.length">
          <img :src="noDataImage" />
          <p>{{ $t('common.base.tip.noSelectedDataFromList') }}</p>
        </div>
        <template v-else>
          <div class="part-selected-list">
            <div class="part-selected-row part-selected-head">
              <span class="part-selected-sn">{{ $t('common.label.serialNumber') }}</span>
              <span class="part-selected-name">{{ $t('common.label.sparePart') }}</span>
            </div>
            <div class="part-selected-row" v-for="c in selected" :key="c.id">
              <span class="part-selected-sn">{{c.sparepart.serialNumber}}</span>
              <span class="part-selected-name">{{c.sparepart.name}}</span>
              <button type="button" class="part-selected-delete" @click="cancelSelectPart(c)">
                <i class="iconfont icon-fe-close"></i>
              </button>
            </div>
          </div>
        </template>
      </div>
    </base-panel>
  </div>
</template>

<script>
// pageDes 备件出入库记录列表
import { isOpenData, openAccurateTab } from '@src/util/platform';
import _ from 'lodash';
import qs from '@src/util/querystring2';
import Page from '@src/model/Page';
import { formatDate, objectDateToTimestamp, dayTimeStart, dayTimeEnd, nearDateBy } from 'pub-bbx-utils';
import AuthUtil from '@src/util/auth';
import { safeNewDate } from '@src/util/time';
import StorageUtil from '@src/util/storageUtil';
/* mixin */
import ThemeMixin from '@src/mixins/themeMixin/index.ts'
import BaseSearchDrawer from 'packages/BaseSearchDrawer/BaseSearchDrawer.vue';
import { checkButtonDisplayed } from '@src/util/dom';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { defaultTableData } from '@src/util/table'

/* export & import */
import { partRepertoryRecprtdExport } from '@src/api/Export';
import TableForStashWidth from '@src/mixins/tableForStashWidth/index.js';

const STORAGE_COLNUM_KEY = 'repe_record_list_column';
const STORAGE_PAGESIZE_KEY = 'repe_record_list_pagesize';

import { isStandardEdition, isExperienceEdition } from '@shb-lib/version'
import { VersionControlSparePartMixin } from '@src/mixins/versionControlMixin'
import { t } from '@src/locales'

let validateText = val=>{
  if(val.length > 20) return val.slice(0, 20);
  return val
}
let validateNumNeg = val=>{
  if(val < -99999) return -99999;
  else if(val > 99999) return 99999
  return val
}
let validateNum = val=>{
  if(val < 0) return 0;
  else if(val > 99999) return 99999
  return val
}
import { getOssUrl } from '@src/util/assets'
const noDataImage = getOssUrl('/no_data.png')
export default {
  name: 'repertory-record-view',
  inject: ['initData'],
  mixins: [
    ThemeMixin, 
    TableForStashWidth,
    VersionControlSparePartMixin
  ],
  data(){
    let pageSize = StorageUtil.get(STORAGE_PAGESIZE_KEY) || 10;

    let originModel = {
      keyWord: '',
      type: '',
      sparepartType: '',
      item: '',
      enable: '',
      pageNum: 1,
      propser:'', // 发起人
      remark:'', // 备注
      name:'', // 仓库
      sourceName:'', // 原仓库
      targetName:'', // 目标库
      variation:'', // 变化
      number:'', // 结余
      pageSize,
      approveNo: '' //  申请编号
    };

    return {
      defaultTableData,
      noDataImage,
      isButtonDisplayed: checkButtonDisplayed(),
      isOpenData,
      selectColumnState: 'partV2_repertoryRecortList',
      multipleSelectionPanelShow: false,
      selectedLimit: 500,
      isPersonalRepertory: false,
      auths: [],
      columns: [],
      isExpand: false,
      pending: false,
      
      types: [],
      user: {
        userId: '',
        loading: false,
        options: []
      },
      sparepart: {
        sparepartId: '',
        loading: false,
        options: []
      },
      originModel,
      model: _.assign({}, originModel),

      page: new Page(),
      selected: [],
      instockDialog: false,
      outstockDialog: false,
      repertory:[],
      repertorySelected:'',
      sparepartConfig:{},
      outStoreType:'',
      inStoreType:'',
      repertoryName:'',
      pickerOptions2: {
        shortcuts: [{
          text: t('common.base.aboutTime.nearlyWeek'),
          onClick(picker) {
            const end = safeNewDate();
            const start = safeNewDate();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: t('common.base.aboutTime.nearlyMonth'),
          onClick(picker) {
            const end = safeNewDate();
            const start = safeNewDate();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: t('common.base.aboutTime.lastThreeMonths'),
          onClick(picker) {
            const end = safeNewDate();
            const start = safeNewDate();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      timeValue: [],

      exportIds: [],
      partRepertoryRecprtdExport,
      pageLoading:true,
      tableContainerHeight:'440px',
    }
  },
  computed: {
    // 是否允许导入导出
    allowImportAndExport(){
      return AuthUtil.hasAuth(this.auths, 'STOCK_IN_OUT_EXPORT')
    },
    isStandardEdition() {
      return isStandardEdition()
    },
    isExperienceEdition() {
      return isExperienceEdition()
    }
  },
  watch:{
    'model.sourceName':{
      handler(val){
        this.model.sourceName = validateText(val);
      }
    },
    'model.name':{
      handler(val){
        this.model.name = validateText(val);
      }
    },
    'model.remark':{
      handler(val){
        this.model.remark = validateText(val);
      }
    },
    'model.targetName':{
      handler(val){
        this.model.targetName = validateText(val);
      }
    },
    'model.variation':{
      handler(val){
        this.model.variation = validateNumNeg(val);
      }
    },
    'model.number':{
      handler(val){
        this.model.number = validateNum(val);
      }
    }
  },
  methods: {
    clickFnc(item){
      // this.$platform.openTab({
      //   id: 'M_VIP_SPAREPART_APPLY',
      //   title: '办理出入库',
      //   close: true,
      //   url: `/partV2/repertory/apply?approveNo=${item.approveNo}&action=applyDetail`
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageSparepartApply,
        params: `approveNo=${item.approveNo}&action=applyDetail`,
      })
    },
    // 关闭高级搜索弹框
    closeDrawer(){
      this.isExpand = false;
    },
    // 打开工单详情
    openTaskDetail(item){
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `task_view_${item.taskId}`,
      //   title: `工单${item.taskNo}`,
      //   close: true,
      //   url: `/task/view/${item.taskId}?noHistory=1`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskView,
        key: item.taskId,
        titleKey: item.taskNo,
        params: 'noHistory=1',
        fromId
      })    
    },
    // 打开客户详情
    openCustomerDetail(customerId){
      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: `customer_view_${customerId}`,
      //   title: '客户详情',
      //   close: true,
      //   url: `/customer/view/${customerId}?noHistory=1`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: customerId,
        params: 'noHistory=1',
        fromId
      })
    },
    cancelSelectPart(part) {
      if (!part || !part.id) return;
      this.selected = this.selected.filter(ms => ms.id !== part.id);
      this.toggleSelection([part]);
    },
    toggleSelection(rows) {
      let isNotOnCurrentPage = false;
      let row = undefined;

      if (rows) {
        for(let i = 0; i < rows.length; i++) {
          row = rows[i];
          isNotOnCurrentPage = this.page.list.every(item => {
            return item.id !== row.id;
          })
          if(isNotOnCurrentPage) return
        }
        rows.forEach(row => {
          this.$refs.table.toggleRowSelection(row);
        });
      } else {
        this.$refs.table.clearSelection();
        this.selected = [];
      }
    },
    // select part
    handleSelection(selection) {
      let tv = this.computeSelection(selection);
      // 在需要限制最多选择500个备件时，取消function内部全部注释即可
      let original = this.selected
        .filter(ms => this.page.list.some(cs => cs.id === ms.id));
      let unSelected = this.page.list
        .filter(c => original.every(oc => oc.id !== c.id));

      if (tv.length > this.selectedLimit) {
        this.$nextTick(() => {
          original.length > 0
            ? unSelected.forEach(row => {
              this.$refs.table.toggleRowSelection(row, false);
            })
            : this.$refs.table.clearSelection();
        })
        return this.$platform.alert(t('common.base.tip.maxDataCanChooseTips', {data1:this.selectedLimit}));
      }
      this.selected = tv;

      this.$refs.baseSelectionBar?.openTooltip();
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    },
    computeSelection(selection) {
      let tv = [];
      tv = this.selected
        .filter(ms => this.page.list.every(c => c.id !== ms.id));
      tv = _.uniqWith([...tv, ...selection], _.isEqual);
      return tv;
    },
    matchSelected() {
      if (!this.selected.length) return;
      const selected = this.page.list
        .filter(c => {
          if (this.selected.some(sc => sc.id === c.id)) {
            this.selected = this.selected.filter(sc => sc.id !== c.id);
            this.selected.push(c);
            return c;
          }
        }) || [];

      this.$nextTick(() => {
        this.toggleSelection(selected);
      });
    },

    chooseColnum(column){
      this.trackEventHandler('selectColumn');

      column.show = !column.show;
      this.saveColumnStatusToStorage();
      // let data = {};
      // this.columns.forEach(item => data[item.field] = item.show)
      // StorageUtil.save(STORAGE_COLNUM_KEY, data);
    },
    seeTime() {
      const [timeStart, timeEnd] = this.timeValue || [];
      this.model.timeStart = timeStart;
      this.model.timeEnd = timeEnd

    },

    chooseUser(value){
      if(this.user.userId == value) return;

      this.user.userId = value;
      this.model.executor = value;

    },
    // 选择发起人
    choosePropser(value){
      if(this.model.propser == value) return
      this.model.propser = value;
    },

    openDetail(row){
      // this.$platform.openTab({
      //   id: `partV2_detail_${row.id}`,
      //   url:`/partV2/detail?id=${row.id}`,
      //   title: '备件品类详情'
      // })
      openAccurateTab({
        type: PageRoutesTypeEnum.PagePartV2Detail,
        key: row.id,
        params: `id=${row.id}`,
      })
    },
    // 导出库存记录
    exportData(exportAll){
      if(!this.allowImportAndExport) return;
      let ids = [];

      if(!exportAll){
        if(this.selected.length == 0) return this.$platform.alert(t('common.base.tip.exportUnChooseTip'));
        ids = this.selected.map(item => item.id);
      }
      
      this.$refs.exportPanel.open(ids, `${formatDate(safeNewDate(), 'YYYY-MM-DD')}出入库记录.xlsx`);
    },
    select(data){
      this.selected = data;
    },
    
    initialize(){
      this.loadData();
      // this.fetchRepertory();
      this.fecthSparepartConfig()
      this.fetchUser();
      this.fetchSparepart();
    },
    jump(pageNum){
      this.model.pageNum = pageNum;
      this.loadData();
    },
    pageSizeChange(pageSize){
      this.model.pageSize = pageSize;
      this.originModel.pageSize = pageSize;

      this.loadData();
      StorageUtil.save(STORAGE_PAGESIZE_KEY, pageSize);
    },
    search(){
      this.isExpand = false;
      this.model.pageNum = 1;
      this.loadData();
    },
    reset(){
      this.isExpand = false;
      this.model = _.assign({}, this.originModel);
      this.sparepart.sparepartId = '';
      this.timeValue = [];
      this.user.userId = '';
      this.loadData();
    },
    async loadData(){
      this.pageLoading = true;
      try{
        this.page = await this.fetchData();
        this.model.pageNum = this.page.pageNum;
        this.model.pageSize = this.page.pageSize;
        console.log(this.page)
        this.matchSelected();
      }catch(error){
        console.log(error)
      }
      this.pageLoading = false;
    },
    fecthSparepartConfig(){
      // 获取备件设置
      return this.$http.post('/partV2/repertory/sparepartConfig').then(result => {
        let sparepartConfig = []
        let outStoreType = {}
        let inStoreType = {}
        
        let outstock = []
        let instock = []
        
        if (this._isShowPartBack) {
          instock = instock.concat(['备件退回', '分配退回'])
        }
        
        if (this._isShowSparePartPerson) {
          outstock = outstock.concat(['申领到个人', '分配出库'])
          instock = instock.concat(['分配撤回'])
        }
        
        if (this._isShowPartTransfer) {
          outstock = outstock.concat(['调拨出库'])
          instock = instock.concat(['调拨入库', '调拨退回', '调拨撤回'])
        }
        
        
        if (Array.isArray(result.outStoreType)) {
          outStoreType['options'] = outstock.concat(result.outStoreType)
        }else{
          outStoreType['options'] = outstock;
        }
        if (Array.isArray(result.inStoreType)) {
          inStoreType['options'] = instock.concat(result.inStoreType)
        }else{
          inStoreType['options'] = instock;
        }
        outStoreType['label'] = '出库类型'
        inStoreType['label'] = '入库类型'
        sparepartConfig.push(outStoreType)
        sparepartConfig.push(inStoreType)
        this.sparepartConfig = sparepartConfig;
      })
    },
    fetchData(){
      // 获取出入库记录列表
      const params = objectDateToTimestamp({...this.model}, ['timeStart', 'timeEnd'])
      return this.$http.post('/partV2/repertory/recordData', params).then(result => {
        let list = result.list || [];
        list.forEach(item => item.disabled = false);
        return result;
      })
    },
    fetchRepertory(){
      // 获取仓库类型
      return this.$http.get('/partV2/repertory/listForManager').then(result => {
        this.repertory = result || [];
      })
    },
    fetchUser(keyword){
      // 获取用户
      let model = {
        keyword,
        pageSize: 50
      }
      this.user.loading = true
      this.$http.get('/partV2/repertory/user/list', model)
        .then(result => this.user.options = result.list)
        .catch(err => console.log(err))
        .finally(() => this.user.loading = false);
    },
    fetchSparepart(keyword){
      // 获取备件
      let model = {
        keyWord: keyword,
        enable: 1,
        pageSize: 50
      }
      this.sparepart.loading = true
      this.$http.post('/partV2/repertory/sparepart/list', model)
        .then(result => this.sparepart.options = result.list)
        .catch(err => console.log(err))
        .finally(() => this.sparepart.loading = false);
    },
    chooseRepertory(value){
      this.trackEventHandler('chooseRepertory');

      this.repertoryName = value;
      if(value){
        this.model.repertoryId = value
      }else{
        delete this.model.repertoryId
      }
      this.model.pageNum = 1;
      this.loadData()
    },
    chooseSparepart(value){
      if(this.sparepart.sparepartId == value) return;
      this.sparepart.sparepartId = value;
      this.model.sparepartId = value;
    },
    buildParams(pageNum, pageSize){
      return {
        ...this.model,
        pageNum,
        pageSize
      };
    },
    buildColumns(){
      let localData = StorageUtil.get(STORAGE_COLNUM_KEY) || {};

      let columns = [
        {
          field: 'recordNo',
          label: t('part.field30'),
          show: true,
          minWidth: 220,
          export: true,
        },
        {
          field: 'approveNo',
          label: t('common.form.preview.stock.sparepartStockDisplayName.approveNo'),
          show: true,
          minWidth: 220,
          export: true,
        },
        {
          field: 'sparepart.serialNumber',
          label: t('common.part.partNo'),
          show: true,
          minWidth: 150,
          export: true,
        },
        {
          field: 'sparepart.name',
          label: t('common.fields.partName.displayName'),
          show: true,
          minWidth: 150,
          export: true,
        },
        {
          field: 'sparepart.type',
          label: t('common.label.sparepartType'),
          show: true,
          minWidth: 100,
          export: true,
        },
        {
          field: 'sparepart.standard',
          label: t('common.label.sparepartStandard'),
          show: true,
          minWidth: 100,
          export: true,
        },
        {
          field: 'type',
          label: t('common.part.category'),
          show: true,
          minWidth: 100,
          export: true,
        },
        {
          field: 'item',
          label: t('common.label.type'),
          show: true,
          minWidth: 100,
          export: true,
        },
        {
          field: 'repertory.name',
          label: t('common.base.warehouse'),
          show: true,
          minWidth: 120,
          export: true,
        },
        {
          field: 'sourceName',
          label: t('part.field26'),
          show: true,
          minWidth: 120,
          export: true,
        },
        {
          field: 'targetName',
          label: t('part.field8'),
          show: true,
          minWidth: 120,
          export: true,
        },
        {
          field: 'variation',
          label: t('part.field33'),
          show: true,
          minWidth: 80,
          export: true,
        },
        {
          field: 'number',
          label: t('part.field34'),
          show: true,
          minWidth: 80,
          export: true,
        },
        {
          field: 'taskNo',
          label: t('common.task.taskNo'),
          show: true,
          minWidth: 80,
          width: 150,
          isPersonalRepertory: true,
          export: true,
        },
        {
          field: 'customerName',
          label: t('part.field39'),
          show: true,
          minWidth: 80,
          width: 150,
          isPersonalRepertory: true,
          export: true,
        },
        {
          field: 'customerNumber',
          label: t('common.fields.customerNo.displayName'),
          show: true,
          minWidth: 80,
          width: 150,
          isPersonalRepertory: true,
          export: true,
        },
        {
          field: 'propserName',
          label: t('common.label.sponsor'),
          show: true,
          minWidth: 120,
          export: true,
        },
        {
          field: 'executorName',
          label: t('common.form.preview.stock.sparepartStockDisplayName.approveName'),
          show: true,
          minWidth: 120,
          export: true,
        },
        {
          field: 'applyRemark',
          label: t('part.text19'),
          show: true,
          minWidth: 120,
          showTip: false,
          export: true,
        },
        {
          field: 'remark',
          label: t('common.form.preview.sparepart.colum21'),
          show: true,
          minWidth: 120,
          showTip: false,
          export: true,
        },
        {
          field: 'createTime',
          label: t('common.label.time'),
          show: true,
          width: 180,
          export: true,
        }
      ]
      
      columns.forEach(column => {
        let isShow = localData[column.field];
        if(typeof isShow == 'boolean') column.show = isShow;
      })

      if(this.isPersonalRepertory){
        columns = columns.filter(item => item.isPersonalRepertory !== false)
      }

      return columns;
    },
    // TalkingData事件埋点
    trackEventHandler (type) {
      switch (type) {
      case 'search':
        this.$tdOnEvent('pc：出入库记录-搜索事件');
        break;
      case 'reset':
        this.$tdOnEvent('pc：出入库记录-重置事件');
        break;
      case 'advSearch':
        this.$tdOnEvent('pc：出入库记录-高级搜索事件');
        break;
      case 'chooseRepertory':
        this.$tdOnEvent('pc：出入库记录-仓库筛选下拉框事件');
        break;
      case 'selectColumn':
        this.$tdOnEvent('pc：出入库记录-选择列事件');
        break;
      case 'moreAction':
        this.$tdOnEvent('pc：出入库记录-更多操作事件');
        break;                                                  
      default:
        break;
      }
    },
    // 构建表格列
    buildTableColumn() {
      let baseColumns = this.buildColumns();
      const localStorageData = this.getLocalStorageData();
      let columnStatus = (localStorageData.columnStatus && localStorageData.columnStatus[this.selectColumnState]) || [];
      let localColumns = columnStatus
        .map(i => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col) => (acc[col.field] = col) && acc, {});
      let columns = [...baseColumns].map(col => {
        let show = col.show;
        let width = col.width;
        let localField = localColumns[col.field];
        if (null != localField) {
          width = typeof localField.width == 'number'
            ? `${localField.width}px`
            : `${localField.width}`.indexOf('px') ? localField.width : '';
          show = localField.show !== false;
        }
        col.show = show;
        col.width = width;
        col.type = 'column';

        return col;
      });

      if (this.isBasicEditionHideProduct) {
        columns = columns.filter(item => item.field !== 'esProductEntities')
      }

      return columns;
    },
    /**
     * @des 获取列表当前的可滚动高度
     */
		 knowTableContainerHeight(){
      let min = 440;
      try {
        let window_ = window.innerHeight;
        let header = this.$refs.tableHeaderContainer?.offsetHeight || 0;
        let do_ = this.$refs.tableDoContainer?.offsetHeight || 0;
        let footer = this.$refs.tableFooterContainer?.offsetHeight || 0;
        let selection = this.$refs.BaseSelectionBarComponent?.offsetHeight || 0;
        // selection = selection ? selection + 8 : selection;
        min = window_ - header * 1 - do_ * 1 - footer * 1 - selection * 1 - 20 - 10 ;
        console.log(window_, header, do_, footer, selection, 'window_, header, do_, footer, selection');
        console.log(min, 'min')
        min = min > 440 ? min : 440;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'tableContainerHeight', `${min}px`)
    },
    changePackUp(){
      this.packUp = !this.packUp;
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    }
  },
  async created(){
    let initData = this.initData;
    const href = window.location.href;
    if(href.indexOf('?fromId') > -1){
      this.model.keyWord = href.split('?fromId=')[1];
    }

    this.types = initData.sparepartType || [];
    this.auths = initData.auths || [];
    this.isPersonalRepertory = initData.isPersonalRepertory;

    this.columns = this.buildColumns();
    try{
      await this.fetchRepertory();
    }catch(error){
      console.log(error)
    }

    let urlParams = qs.parse(window.location.search);

    if(urlParams.startTime && urlParams.endTime && urlParams.type) {
      this.isExpand = true;
      const startTime = (+dayTimeStart(/^[0-9]$/.test(urlParams.startTime)) ? +urlParams.startTime : urlParams.startTime);
      const endTime = (+dayTimeEnd(/^[0-9]$/.test(urlParams.endTime)) ? +urlParams.endTime : urlParams.endTime);
      this.timeValue = [startTime, endTime];
      this.model.type = urlParams.type;             
    } else {
      // 默认日期筛选3个月
      const startTime = +nearDateBy(3, 'month')
      const endTime = +dayTimeEnd();
      this.timeValue = [startTime, endTime];
    }

    this.seeTime();

    if(urlParams.id){
      this.repertoryName = urlParams.id; 
      this.model.repertoryId = urlParams.id

      let flag = this.repertory.some((item) => {
        return item.id == urlParams.id;
      });
      if(!flag) {
        this.repertoryName = ''; 
        delete this.model.repertoryId; 
        this.$message.warning({message:t('part.tips89'), duration:0, showClose:true});  
      }
    }else{
      delete this.model.repertoryId;
    }   
    this.columns = this.buildTableColumn();
    this.initialize();  
  },
  mounted() {
    let that_ = this;
    // 监听切换后需要重新计算列表高度 后续可以用activated生命周期替换
    window.addEventListener('message', (event)=> {
      const {action, data} = event.data;
      if (action == 'shb.frame.activatedPage'){
        that_.$nextTick(()=> {
          that_.knowTableContainerHeight();
        })
      }
    });
    this.$nextTick(()=> {
      this.knowTableContainerHeight()
      window.onresize = _.debounce(()=>{
        that_.knowTableContainerHeight()
      }, 500)
    })
  },
  components:{
    [BaseSearchDrawer.name]:BaseSearchDrawer
  }
}
</script>

<style lang="scss">
.no-padding{
  padding:0;
}
.srp-user-item{
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
  padding: 2px 0;
  justify-content: space-between;

  &:last-child{
    margin: 0;
  }

  img{
    display: block;
    width: 28px;
    height: 28px;
    border-radius: 2px;
  }

  p{
    flex: 1;
    margin: 0;
    margin-left: 10px;
    font-weight: 500;
    font-size: 14px;
    overflow: hidden;
    line-height: 28px;
    width:0;
  }
}

.page .base-search-repertory-picker {
  width: 300px;

  .el-range-editor--small.el-input__inner{
    height: 34px;
  }

  .el-range-separator {
    line-height: 27px;
  }
}
.page .customer-list-base-search-group {
  justify-content: left !important;
}

.srp-list-form{
  width: 720px;
  display: inline-block;

  .srp-list-form-item{
    margin-right: 5px;
  }
}

.customize-el-dropdown-btn {
  padding: 0 15px;
  line-height: 32px;
  display: inline-block;
  background: $color-primary-light-9;
  color: $text-color-primary;
  outline: none;
  margin-left: 5px;
  .iconfont {
    margin-left: 5px;
    font-size: 12px;
  }

  &:hover {
    cursor: pointer;
    color: #fff;
    background: $color-primary;
  }
}

.part-option{
  margin: 5px 0;

  p{
    overflow: hidden;
    margin: 0;
    line-height: 24px;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}


// -------- part selected panel --------
.part-selected-count {
  @include fontColor();
  padding: 0 3px;
  width: 15px;
  text-align: center;
  cursor: pointer;
  font-size: 13px;
}

.part-selected-panel {
  font-size: 14px;
  height: calc(100% - 51px);

  .part-selected-tip {
    padding-top: 80px;

    img {
      display: block;
      width: 160px;
      margin: 0 auto;
    }

    p {
      text-align: center;
      color: $text-color-regular;
      margin: 8px 0 0 0;
      line-height: 20px;
    }
  }

  .part-selected-list {
    height: 100%;
    padding: 10px;
    overflow-y: auto;

    .part-selected-row {
      display: flex;
      flex-flow: row nowrap;
      line-height: 36px;
      border-bottom: 1px solid #ebeef5;
      font-size: 13px;

      &:hover {
        background-color: #f5f7fa;

        .part-selected-delete {
          visibility: visible;
        }
      }
    }

    .part-selected-head {
      background-color: #F0F5F5;
      color: #333;
      font-size: 14px;
    }

    .part-selected-sn {
      padding-left: 10px;
      width: 150px;
      @include text-ellipsis;
    }

    .part-selected-name {
      padding-left: 10px;
      flex: 1;
      @include text-ellipsis;
    }

    .part-selected-delete {
      width: 36px;
    }

    .part-selected-row button.part-selected-delete {
      padding: 0;
      width: 36px;
      height: 36px;
      border: none;
      background-color: transparent;
      outline: none;
      color: #646B78;
      visibility: hidden;

      i {
        font-size: 14px;
      }

      &:hover {
        color: #e84040;
      }
    }
  }
}

.part-panel-btn {
  float: right;
  cursor: pointer;
  width: 16px;
  height: 16px;
  background: url("../../../assets/img/clear.png") no-repeat center;
  background-size: cover;

  &:hover {
    background: url("../../../assets/img/clear-hover.png") no-repeat center;
    background-size: cover;
  }
}

</style>
<style lang="scss" scoped>
.el-dropdown-link {
  line-height: 31px;
  display: inline-block;
  outline: none;
}
.base-search-group-container .base-search {
  justify-content: flex-end;
}
.page{
  overflow:visible;
}
</style>